<?php
/**
 * Created by PhpStorm.
 * User: crystal
 * Date: 2017/9/7
 * Time: 15:56
 */
namespace app\Model;


use lib\DataAccess\DataAccess;
use lib\Application;

abstract class Model
{
    // 数据持久化访问工具对象实例
    private $dataAccess;

    // 当前数据模型对象要持久化存储的目录名
    protected $dataDirectory = '';

    public function __construct()
    {
        $app = Application::getInstance();
        $this->dataAccess = $app->getObject(DataAccess::class);
        $this->dataAccess->setDataDirectory($this->dataDirectory);
    }

    /**
     * 根据指定的查询条件，获取一个用户对象实例
     *
     * @param $condition array 包含条件组合的数组
     * @return User 返回查找到的用户信息对象
     */
    public static function find(Array $condition)
    {
        $modelClass = get_called_class();
        $array = (new $modelClass())->dataAccess->find($condition);
        return $modelClass::fromArray($array);
    }


    public static function get(Array $condition = [])
    {
        $modelClass = get_called_class();
        $array = (new $modelClass())->dataAccess->get($condition);
        $objArray = [];
        foreach ($array as $a) {
            $obj = $modelClass::fromArray($a);
            $objArray[] = $obj;
        }
        return $objArray;
    }

    /**
     * 保存当前相册信息
     */
    public function save()
    {
        $this->dataAccess->save($this->toArray());
    }

    public static abstract function fromArray(Array $array);
    public abstract function toArray();
}